<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /*
                     思路1：使用冒泡排序
                     思路2：双指针，将0放到左边将2放到右边。定义两个指针left和right
                     left永远指向左边，right永远指向右边末尾

                     2  0  2
                     */
      var sortColors = function (nums) {
        let left = 0
        let right = nums.length - 1
        let index = 0
        while (index <= right) {
          if (nums[index] == 0) {
            ;[nums[index], nums[left]] = [nums[left], nums[index]]
            left++
            index++
          } else if (nums[index] == 1) {
            index++
          } else if (nums[index] == 2) {
            /* 遇到2和末尾替换的时候，还需要再次判断 2 0 2 如果index++会跳过 */
            ;[nums[index], nums[right]] = [nums[right], nums[index]]
            right--
          }
        }
        return nums
      }
      console.log(sortColors([2, 0, 2, 1, 1, 0]))
    </script>
  </body>
</html>
